#include "link_list.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int create_node(node_t **p){
    if(NULL == p){
        return -1;
    }
    *p = (node_t *)malloc(sizeof(node_t));
    if(NULL == *p){
        printf("内存不足\n");
        exit(EXIT_FAILURE);
    }
    memset(*p, 0, sizeof(node_t)); // 清空分配的空间 数组中全是'\0' 指针是 NULL
    return 0;
}

// 加载名单到内存中
int load_name(const char *soft_install_path, const char *file_name, node_t *phead){
    if(NULL == phead){
        return -1;
    }
    char pathname[512] = {0};
    sprintf(pathname, "%s/cfg/%s", soft_install_path, file_name);
    FILE *fp = fopen(pathname, "r");
    if(NULL == fp){
        printf("打开名单文件错误\n");
        exit(EXIT_FAILURE);
    }
    node_t *pnew = NULL;
    node_t *ptemp = NULL;
    char buff[32] = {0};
    while(NULL != fgets(buff, sizeof(buff), fp)){
        if('\n' == buff[strlen(buff)-1]){
            buff[strlen(buff)-1] = '\0';
        }
        ptemp = phead;
        while(NULL != ptemp->next){
            ptemp = ptemp->next;
        }
        create_node(&pnew);
        strcpy(pnew->name, buff); // 把读到的名字放到新节点的数据域
        ptemp->next = pnew;
        *(int *)phead->name += 1; // 头结点的数据域中前4字节记录人数
    }
    fclose(fp);
    return 0;
}